<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_data extends CI_Model{

	function __construct(){
		parent::__construct();
		$this->load->database();
	}

	


	/**
	 * [getUserData description]
	 * @param  [array] $param [id,date]
	 * @param  [string] $unit  [week,day,month]
	 * @return [array]        [data]
	 */
	public function getUserData($param,$unit){
		$date = $param['date'];
		// verify unit
		switch ($unit) {
			case 'week':
				if(!preg_match('/^\d{1,2}$/i', $date)){
					// invalid week
					json_return(false,'invalid week');
				}
				$unit = 'WEEK';
				break;
			case 'day':
				if(!preg_match('/^\d{1,3}$/i', $date) ){
					// invalid week
					json_return(false,'invalid day');
				}
				$unit = 'DOY';

				break;
			case 'month':
				if(!preg_match('/^\d{1,2}$/i', $date) ){
					// invalid week
					json_return(false,'invalid month');
				}
				$unit = 'MONTH';

				break;
			case 'year':
				if(!preg_match('/^\d{4}$/i', $date) ){
					// invalid week
					json_return(false,'invalid year');
				}
				$unit = 'YEAR';
				break;
			default:
				break;
		}

		if($unit == 'all'){
			// get all data
			$sql = "select a.data from user_data as a INNER JOIN user_token as b on a.tid=b.tid where a.tid=?  order by a.date asc,a.lastupdate desc";
			$result = $this->db->query($sql,$param['tid'])->result();
		}else{
			// get sport data 
			$sql = "select a.data from user_data as a INNER JOIN user_token as b on a.tid=b.tid where a.tid=? and EXTRACT($unit from a.date)=? order by a.date asc,a.lastupdate desc";
			$result = $this->db->query($sql,$param)->result();
		}

		$data = array();
		// var_dump($result);die;
		
		if($this->db->affected_rows()){
			foreach($result as $v) {
				$data[] = $v->data;

			}
		}

		// get userinfos
		$where = array('tid'=>$param['tid']);
		$info = $this->db->select('version')->get_where('user_infos',$where)->row_array();
		// var_dump($param);die;
		// var_dump($this->db->last_query());die;
		// return result
		$result = array();
		$result['data'] = $data;
		$result['version'] = isset($info['version']) ? $info['version'] : "1.0";


		
		return $result;
		
	}

	

}